package cn.schoolwow.quickapi.module.business.api.flow.single;

import cn.schoolwow.quickapi.module.business.api.domain.API;
import cn.schoolwow.quickapi.module.common.flow.MockDataFlow;
import cn.schoolwow.quickapi.util.QuickAPIUtil;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class SetAPIResponseBodyFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        API api = (API) flowContext.checkData("api");

        Type type = api.method.getGenericReturnType();
        Class clazz = null;
        if (type instanceof ParameterizedType) {
            clazz = api.method.getGenericReturnType().getClass();
            api.returnClassName = api.method.getGenericReturnType().getTypeName();
        }else{
            clazz = api.method.getReturnType();
            api.returnClassName = api.method.getReturnType().getName();
        }

        flowContext.startFlow(new MockDataFlow())
                .putTemporaryData("clazz", clazz)
                .putTemporaryData("methodName", api.method.getName())
                .execute();
        String jsonString = flowContext.getData("jsonString", String.class);
        if(null!=jsonString){
            api.responseBody = QuickAPIUtil.formatAndPrettyJSON(jsonString);
        }
    }

    @Override
    public String name() {
        return "设置返回体内容";
    }
}
